

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { IUser } from 'src/types/user.interface';
import HttpResponse from 'src/types/http.response.interface';

type UnionType = IUser | IUser[];


@Injectable()
export class UserService {

    /**
     * 参数装饰器,User 这个名字要和app.module.ts中的MongooseModule.forFeature 定义的名字一样
     * User 是定义好的
     * @param recommendModel 
     */
    constructor(@InjectModel('User') private userModel: Model<IUser>) {

    }


    /**
     * 查询数据
     * @param queryCondition 
     * @returns 
     */
    async findService(queryCondition?:object): Promise<UnionType> {
        return this.userModel.find(queryCondition).exec();
    }


    /***
     * 向mongodb中插入数据
    */
    async generateCode(phone:string): Promise<UnionType> {
       
        //如果请求体是一个数组
        console.log("传递的参数=",phone);
        const code = Math.floor(100000+Math.random()*900000).toString(); //获得任意6位的数字验证码
        const data = await new this.userModel({phone,code}).save();  //把手机号和生成的code都插入到表中
        return data;
        
    }

    /**
     * 验证输入的验证码是否正确
     * @param phone 
     * @param code 
     * @returns 
     */
    async checkCode(phone:string,code:string):Promise<UnionType>{
        const data = this.userModel.find().where({"phone":phone,"code":code}).select(["phone","code"]).exec();
        console.log('data=',data)
        data.then((res)=>{
            console.log(res)
        })
        return data;
    }



    /**
     * 使用验证码登录接口
     * @param phone 
     * @param code 
     * @returns 
     */
    async loginWithVerifyCode(phone:string,code:string):Promise<UnionType>{
        const data = this.userModel.find().where({"phone":phone,"code":code}).select(["phone","code"]).exec();
        console.log('data=',data)
        data.then((res)=>{
            console.log(res)
        })
        return data;
    }


     /**
     * 使用密码密码登录
     * @param phone 
     * @param password 
     * @returns 
     */
     async loginWithPassword(phone:string,password:string):Promise<UnionType>{
        const data = this.userModel.find().where({"phone":phone,"password":password}).select(["phone","password"]).exec();
        console.log('data=',data)
        data.then((res)=>{
            console.log(res)
        })
        return data;
    }


    async register(phone:string,password:string):Promise<UnionType>{
        const data = await new this.userModel({phone,password}).save();
        return data;
    }




}




